//
//  WmcHomeControlExposureView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/4.
//

import UIKit
import YPBedrock

typealias WmcHomeControlExposureView = WmcHomeControlView.ExposureView
extension WmcHomeControlView {
    class ExposureView: WmcBaseView {
        // Internal

        /// 最大值
        var maxBias: CGFloat = 8
        /// 最小值
        var minBias: CGFloat = -8
        /// 太阳的大小
        var sunRadiusSize: CGFloat = 14
        /// 曝光的回调
        var biseBlock: YPBlock.OneParam<CGFloat>?

        lazy var exposureSlider: UIImageView = {
            let imageView = UIImageView(image: "home_cam_exposure_slider".wmc_image)
            imageView.contentMode = .scaleAspectFit
            return imageView
        }()

        override func makeUI() {
            backgroundColor = .clear
            clipsToBounds = true
            isHidden = true

            addSubview(exposureSlider)
            exposureSlider.snp.makeConstraints { make in
                make.left.right.centerY.equalToSuperview()
            }
        }

        func setSliderCenter(_ centerY: CGFloat) {
            var newCenterY = centerY
            if let beforePointY = beforeOffsetCenterY {
                newCenterY -= beforePointY
            } else {
                updateOffsetCenterY()
            }
            let maxBottom = (frame.height / 2 - sunRadiusSize)
            let maxTop = -maxBottom
            if newCenterY < 0, newCenterY < maxTop {
                newCenterY = maxTop
            } else if newCenterY > 0, newCenterY > maxBottom {
                newCenterY = maxBottom
            }
            exposureSlider.snp.updateConstraints { make in
                make.centerY.equalToSuperview().offset(newCenterY)
            }

            let ratio = -(newCenterY / maxBottom)
            var bise: CGFloat = 0
            if ratio > 0 { // 高曝
                bise = ratio * maxBias
            } else {
                bise = -(ratio * minBias)
            }
            biseBlock?(bise)
        }

        func clearRecord() {
            beforeOffsetCenterY = nil
            exposureSlider.snp.updateConstraints { make in
                make.centerY.equalToSuperview()
            }
        }

        func updateOffsetCenterY() {
            beforeOffsetCenterY = (frame.height / 2) - exposureSlider.center.y
        }

        // Private

        private var beforeOffsetCenterY: CGFloat?
    }
}
